import 'dart:async';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_application_1/components/article_cart.dart';
import 'package:flutter_application_1/config/app_colors.dart';
import 'package:flutter_application_1/services/video_service.dart';

import '../../components/video_cart.dart';
import '../../models/article_model.dart';
import '../../models/video_model.dart';
import '../../services/article_service.dart';

class VideoPage extends StatefulWidget {
  const VideoPage({Key? key}) : super(key: key);

  @override
  _VideoPageState createState() => _VideoPageState();
}

class _VideoPageState extends State<VideoPage>
    with AutomaticKeepAliveClientMixin {
  late EasyRefreshController _controller;
  List<VideoItem> _videoList = VideoList([]).list;
  int page = 1;
  int limit = 10;
  bool hasMore = true;
  bool error = false;
  String errorMsg = '';
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _controller = EasyRefreshController(
        controlFinishLoad: true, controlFinishRefresh: true);
    _getVideos();
  }

  Future _getVideos({bool push = false}) async {
    List<dynamic> result = await VideoService.getVideos(page: page);
    VideoList videoListModel = VideoList.fromJson(result);
    setState(() {
      //hasMore
      page++;
      if (push) {
        _videoList.addAll(videoListModel.list);
      } else {
        _videoList = videoListModel.list;
      }
    });
  }

  FutureOr _onRefresh() async {
    page = 1;
    await _getVideos();
    _controller.finishRefresh();
    _controller.resetFooter();
  }

  FutureOr _onLoad() async {
    await _getVideos(push: true);
    _controller.finishLoad();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return EasyRefresh(
      controller: _controller,
      header: ClassicHeader(),
      footer: ClassicFooter(),
      onRefresh: _onRefresh,
      onLoad: _onLoad,
      child: ListView.builder(
        itemCount: _videoList.length,
        itemBuilder: (BuildContext context, int index) {
          return Container(
            margin: EdgeInsets.symmetric(vertical: 6, horizontal: 6),
            child: VideoCart(
              videoItem: _videoList[index],
            ),
          );
        },
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
